//
//  LZManagePicturesViewController.m
//  laziz_Merchant
//
//  Created by xbn_iMac on 2017/3/2.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZManagePicturesViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "UIButton+TransitionEdgeInsets.h"
#import "HTHorizontalSelectionList.h"
#import "extobjc.h"
#import "Masonry.h"
#import "LZManagePictureContentViewController.h"
#import "LZUploadImagePresenter.h"
#import "LZActionSheet.h"
#import "LZImagePickerManager.h"
#import "LZUploadImagePresenter.h"
#import "LZUserModel.h"
#import "LZAlertView.h"
#import "LZManagePicturePresenter.h"
#import "MBProgressHUD.h"
#import "UIControl+BlocksKit.h"

@interface LZManagePicturesViewController ()<HTHorizontalSelectionListDelegate,HTHorizontalSelectionListDataSource,LZPictureManagerDelegate>

@property (nonatomic, strong) UIButton *nav_right_edit_button;
@property (nonatomic, strong) UIButton *nav_right_add_button;

@property (weak, nonatomic) IBOutlet HTHorizontalSelectionList *horizontalSelectionView;

@property (weak, nonatomic) IBOutlet UIView *containerView;

@property (strong, nonatomic) NSMutableArray *horizontalSelectionTitles;

@property (strong, nonatomic) NSArray<__kindof UIViewController *> *contentVCs;

@property (weak, nonatomic) LZActionSheet *actionSheet;

@property (strong, nonatomic) LZImagePickerManager *pictureManager;

@property (strong, nonatomic) UIImage *resultImage;



/**
 当前是否是编辑状态
 */
@property (assign, nonatomic) BOOL isEdit;


/**
 当前选择的是第几个
 */
@property (assign, nonatomic) NSInteger currentIndex;

@property (strong, nonatomic) LZManagePictureContentViewController *dishesVC;
@property (strong, nonatomic) LZManagePictureContentViewController *atmosphereVC;
@property (strong, nonatomic) LZManagePictureContentViewController *menuVC;


@property (assign, nonatomic) NSInteger dishNum;
@property (assign, nonatomic) NSInteger atmosphereNum;
@property (assign, nonatomic) NSInteger menuNum;
@end

@implementation LZManagePicturesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"照片管理页面";
    
    [self configNavigationBar];
    
    [self configData];
    
    [self configUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.selectPictureBlock) {
        _dishesVC.isSingleSelected = YES;
        _dishesVC.isEdit = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
}

#pragma mark - Privite Method

- (LZActionSheet *)actionSheet {
    if (_actionSheet == nil) {
        LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _actionSheet = sheet;
        [_actionSheet creatHeaderWithTitle:LZLocalizedString(@"res_auth_choose_img_sheet_title", nil) andHeight:51];
        [[UIApplication sharedApplication].keyWindow addSubview:_actionSheet];
        
        @weakify(self)
        _actionSheet.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
            @strongify(self)
            if (indexPath.section == 0) {
                UIImagePickerControllerSourceType sourceType = 0;
                
                // 判断是否支持相机
                if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    
                    if (indexPath.row == 0) {
                        // TakePhotos
                        sourceType = UIImagePickerControllerSourceTypeCamera;
                    } else if (indexPath.row == 1) {
                        // PhotoAlbums
                        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    }
                } else {
                    if (indexPath.row == 0) {
                        return;
                    } else {
                        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                    }
                }
                
                [self.pictureManager choosePictureWithSourceType:sourceType andPresenterVC:self];
            }
        };
    }
    
    return _actionSheet;
}

- (LZImagePickerManager*)pictureManager {
    if (_pictureManager) {
        return _pictureManager;
    }
    LZImagePickerManager *manager = [[LZImagePickerManager alloc] init];
    manager.allowsEditing = NO;
    manager.delegate = self;
    _pictureManager = manager;
    return _pictureManager;
}



- (void)configNavigationBar {
    if (!self.selectPictureBlock) {
        self.umLogPageViewName = @"照片管理列表";
        self.title = LZLocalizedString(@"home_menu_manage_pictures", nil);
        
        self.nav_right_edit_button = [UIButton buttonWithType:UIButtonTypeCustom];
        self.nav_right_edit_button.frame = CGRectMake(0, 0, 40, 40);
        [self.nav_right_edit_button addTarget:self action:@selector(navbarEditButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
        UIImage *image_edit = [UIImage imageNamed:@"managepic_nav_edit_normal"];
        [self.nav_right_edit_button setImage:image_edit forState:UIControlStateNormal];
        [self.nav_right_edit_button setNormalImageEdgeInsets:UIEdgeInsetsMake(0, CGRectGetWidth(self.nav_right_edit_button.bounds)-image_edit.size.width, 0, 0)];
        
        
        self.nav_right_add_button = [UIButton buttonWithType:UIButtonTypeCustom];
        self.nav_right_add_button.frame = CGRectMake(0, 0, 40, 40);
        [self.nav_right_add_button addTarget:self action:@selector(navbarAddButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
        UIImage *image_add = [UIImage imageNamed:@"managepic_nav_add"];
        [self.nav_right_add_button setImage:image_add forState:UIControlStateNormal];
        [self.nav_right_add_button setNormalImageEdgeInsets:UIEdgeInsetsMake(0, CGRectGetWidth(self.nav_right_add_button.bounds)-image_add.size.width, 0, 0)];
        
        [self navigationItemSetting:@[self.nav_right_add_button,self.nav_right_edit_button] type:NAVIGATIONITEMSETTING_RIGHT];
    }else{
        UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        confirmButton.frame = CGRectMake(0, 0, 100, 40);
        [confirmButton setTitle:LZLocalizedString(@"confirm", @"") forState:UIControlStateNormal];
        [confirmButton sizeToFit];
        @weakify(self)
        [confirmButton bk_addEventHandler:^(id sender) {
            @strongify(self)
            LZManagePictureContentViewController *currentVC = self.contentVCs[self.currentIndex];
            
            NSArray *imageUrls = [currentVC fetchSelectImageUrls];
            
            if (imageUrls.count > 0) {
                self.selectPictureBlock(imageUrls.count > 0 ?imageUrls[0]:nil);
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        } forControlEvents:UIControlEventTouchUpInside];
        
        [self navigationItemSetting:@[confirmButton] type:NAVIGATIONITEMSETTING_RIGHT];
    }
}

- (void)configData {

    _horizontalSelectionTitles = @[[NSString stringWithFormat:@"%@()",LZLocalizedString(@"res_photo_dishes", @"")],
                                   [NSString stringWithFormat:@"%@()",LZLocalizedString(@"res_photo_atmosphere", @"")],
                                   [NSString stringWithFormat:@"%@()",LZLocalizedString(@"res_photo_menu", @"")]].mutableCopy;
    
    
    [self refreshTitleForTitleNumber];

}

-(void)configUI{
    [_horizontalSelectionView setScrollViewColor:UIColorFromRGB(0xffffff, 1)];
    _horizontalSelectionView.isEqualWidth = YES;
    _horizontalSelectionView.equalWidth = SCREEN_WIDTH/3;
    _horizontalSelectionView.enableScroll = NO;
    _horizontalSelectionView.delegate = self;
    _horizontalSelectionView.dataSource = self;
    
    /*
     ==========================================add child vc=================================================
     */
    
    _dishesVC = [[LZManagePictureContentViewController alloc]initWithNibName:@"LZManagePictureContentViewController" bundle:nil];
    _atmosphereVC = [[LZManagePictureContentViewController alloc]initWithNibName:@"LZManagePictureContentViewController" bundle:nil];
    _menuVC = [[LZManagePictureContentViewController alloc]initWithNibName:@"LZManagePictureContentViewController" bundle:nil];
    
    //    1菜品 2 环境 3 菜单 4 头图 5 营业执照
    
    _dishesVC.index = 1;
    
    _atmosphereVC.index = 2;
    
    _menuVC.index = 3;
    
    _contentVCs = @[_dishesVC,_atmosphereVC,_menuVC].mutableCopy;
    
    
    [self chooseVC:_dishesVC];
}




/**
 上传图片文件

 @param img 图片
 */
- (void)uploadImg:(UIImage *)img
{
    //上传头像
    LZUploadImagePresenter *uploadImagePresenter = [[LZUploadImagePresenter alloc] init];
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    @weakify(self);
    [uploadImagePresenter uploadImage:img
                        andBusinessId:[LZUserModel Instance].sellerId
                      andBusinessType:@"5"
                        andBusinessNo:@"1"
                           andIsThumb:YES
                              andSize:CGSizeZero
                         andonSuccess:^(id data) {
                             @strongify(self);
                             //上传成功获取路径
                             NSArray *resultArray = data[@"data"];
                             if (resultArray.count>0) {
                                 NSDictionary *dic = resultArray[0];
                                 NSString *smallFilePath = dic[@"imgMinPath"];
                                 NSString *bigFilePath = dic[@"filePath"];
                                 NSString *imageUrlAggregation = [NSString stringWithFormat:@"%@&&%@",smallFilePath,bigFilePath];
                                 
                                 [self addPicture:imageUrlAggregation];
                             }
                             [self stopLoadingViewForView:self.view];
                             
                         } onFail:^(NSString *fail) {
                             
                             [self stopLoadingViewForView:self.view];
                             [self uploadLicenseFailureAction];
                             
                         }];
}


-(void)refreshTitleForTitleNumber{
    LZManagePicturePresenter *presenter = [LZManagePicturePresenter new];
    
    [presenter getPictureNumWithSellId:[LZUserModel Instance].sellerId Success:^(id data) {
        
        self.dishNum = [data[@"foodNum"] integerValue];
        self.atmosphereNum = [data[@"envNum"] integerValue];
        self.menuNum = [data[@"menuNum"] integerValue];
        
        self.horizontalSelectionTitles = @[
                                           [NSString stringWithFormat:@"%@(%ld)",LZLocalizedString(@"res_photo_dishes", @""),self.dishNum],
                                           [NSString stringWithFormat:@"%@(%ld)",LZLocalizedString(@"res_photo_atmosphere", @""),self.atmosphereNum],
                                           [NSString stringWithFormat:@"%@(%ld)",LZLocalizedString(@"res_photo_menu", @""),self.menuNum],
                                           ].mutableCopy;
        
        [self.horizontalSelectionView reloadData];
    } Failure:^(NSString *fail) {
        DLog(@"%@",fail);
    }];
}


/**
 上传图片地址到后台

 @param imageUrlAggregation 拼合的缩略图和原图的地址  e.g. xxxx && xxxx
 */
-(void)addPicture:(NSString *)imageUrlAggregation{
    LZManagePicturePresenter *picturePresenter = [LZManagePicturePresenter new];
    
    NSInteger currentVCIndex = self.currentIndex + 1;
    
    [picturePresenter addPictureWithSellId:[LZUserModel Instance].sellerId andPhotoType:[NSString stringWithFormat:@"%ld",currentVCIndex] andPhotoUrls:@[imageUrlAggregation] andToken:[LZUserModel Instance].userToken Success:^(id data) {
        
        LZManagePictureContentViewController *currentVC = self.contentVCs[self.currentIndex];
        
        [currentVC refreshPictureData];
        
        //添加成功后刷新title的照片数量
        [self refreshTitleForTitleNumber];
        
    } Failure:^(NSString *fail) {
        DLog(@"%@",fail);
        
        if ([fail isEqualToString:@"0400026"]) {
            [self showErrorForOverMaxCount];
        }
    }];
}


/**
 执照提交失败,从新提交
 */
- (void)uploadLicenseFailureAction
{
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_license_upload_failure", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    @weakify(self)
    alert.clickButtonIndexBlock = ^(NSInteger index){
        @strongify(self)
        if (index == 1) {
            if (self.resultImage) {
                [self uploadImg:self.resultImage];
            }
        }
    };
}


/**
 修改编辑状态
 */
-(void)changeEditStatus{
    LZManagePictureContentViewController *currentVC = self.contentVCs[self.currentIndex];
    
    currentVC.isEdit = self.isEdit;
    
    [self.nav_right_edit_button setImage:[UIImage imageNamed:self.isEdit?@"managepic_nav_del_highlight":@"managepic_nav_edit_normal"] forState:UIControlStateNormal];
}


#pragma mark - Event

- (void)navbarEditButtonClickAction:(UIButton*)sender {
    
    if (self.isEdit) {
        //删除操作
        LZManagePictureContentViewController *currentVC = self.contentVCs[self.currentIndex];
        
        [currentVC deleteOperation:^{
            //删除成功后刷新title的照片数量
            [self refreshTitleForTitleNumber];
        }];
    }
    
    self.isEdit = !self.isEdit;
    
    [self changeEditStatus];
    
}

- (void)navbarAddButtonClickAction:(UIButton*)sender {
    
    
    NSInteger currentCount;
    
    switch (self.currentIndex) {
        case 0:
            currentCount = self.dishNum;
            break;
        case 1:
            currentCount = self.atmosphereNum;
            break;
        case 2:
            currentCount = self.menuNum;
            break;
        default:
            currentCount = -1;
            break;
    }
    
    if (currentCount >= 30) {
        [self showErrorForOverMaxCount];
        
        return;
    }
    
    
    [self.actionSheet ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"change_takephoto", nil), LZLocalizedString(@"res_auth_phone_album", nil)], @[LZLocalizedString(@"cancel", nil)]]];
    [self.actionSheet ShowView];
    
    self.isEdit = NO;
    
    [self changeEditStatus];
    
}


/**
 选择你目标的child vc
 
 @param willShowViewController 你将要选中的vc
 */
-(void)chooseVC:(UIViewController *)willShowViewController{
    
    if (![self.childViewControllers containsObject:willShowViewController]) {
        [self addChildViewController:willShowViewController];
        [willShowViewController didMoveToParentViewController:self];
    }
    
    [self.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj != willShowViewController) {
            [obj.view removeFromSuperview];
        }
    }];
    
    [self.containerView addSubview:willShowViewController.view];
    
    [willShowViewController.view makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}



/**
 显示错误提醒 ，关于超过10张图片的。
 */
-(void)showErrorForOverMaxCount{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabel.text = LZLocalizedString(@"error_over_max_count", nil);
    [hud showAnimated:YES];
    [hud hideAnimated:YES afterDelay:2.5];
}


#pragma
#pragma mark HTHorizontalSelectionListDelegate

-(NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList{
    return _horizontalSelectionTitles.count;
}

-(NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index{
    
    return _horizontalSelectionTitles[index];
}


-(void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index{
    if (index != _currentIndex) {

        self.isEdit = NO;
        
        [self changeEditStatus];
    }
    
    self.currentIndex = index;
    [self chooseVC:self.contentVCs[index]];
    
    //如果是单选选择的时候
    if (self.selectPictureBlock) {
        LZManagePictureContentViewController *currentVC = self.contentVCs[self.currentIndex];
        currentVC.isSingleSelected = YES;
        currentVC.isEdit = YES;
    }
}

#pragma
#pragma mark LZPictureManagerDelegate

-(void)LZPictureManagerFinishPickingMediaWithInfo:(NSDictionary *)info{
    self.resultImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (self.resultImage) {
        [self uploadImg:self.resultImage];
    }
}


@end
